import Vue from 'vue'
import Vuex from 'vuex'
import {commonApi} from '@/api'
import {tokenManager} from '@/libs/http'
import question from "@/store/modules/questionWeb";
import user from "@/store/modules/user";
import args from "@/store/modules/args";
import Storage from "@/libs/Storage";
import utils from "@/libs/utils";
import {productApi} from "@/api";
import productUtils from "../libs/productUtils";

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    question,
    user,
    args
  },
  state: {
    schoolId: null,
    coachId: null,
    schoolHomeInit: false,
    mine: null,
    env: null,
    systemInfo: {},
    topBar: {},
    location: {
      name: '北京',
      code: 110000
    },
    GPSLocation: null,
    kemu1: null,
    kemu2: null,
    kemu3: null,
    selectedLocation: null,
    questionSetting: {
      fontSize: 0,
      trueNext: true
    },
    settings: {
      kemu1PassScore: '0',
      kemu1TimeMax: '0',
      kemu1NoPassScore: '0',
      kemu4PassScore: '0',
      kemu4TimeMax: '0',
      kemu4NoPassScore: '0',
    },
    settingsInited: false,
    query: {},
    checkedLogined: false,
    vipProducts: [],
    tiyanProduct: null,
    currentTime: Date.now()
  },
  mutations: {
    env(state, env) {
      state.env = env;
    },
    vipProducts(state, vipProducts) {
      state.vipProducts = vipProducts;
    },
    currentTime(state, currentTime) {
      state.currentTime = currentTime;
    },
    tiyanProduct(state, tiyanProduct) {
      state.tiyanProduct = tiyanProduct;
    },
    setKemu1(state, kemu1) {
      state.kemu1 = kemu1;
    },
    setKemu2(state, kemu2) {
      state.kemu2 = kemu2;
    },
    setKemu3(state, kemu3) {
      state.kemu3 = kemu3;
    },
    login(state, {user}) {
      state.mine = user;
    },
    settings(state, {settings}) {
      state.settings = settings;
      state.settingsInited = true
    },
    query(state, {query}) {
      state.query = query || {};
      // if (query.schoolId) {
      //   state.schoolId = query.schoolId
      //   state.coachId = null
      //   Storage.set('schoolHome', {
      //     type: 'school',
      //     id: query.schoolId
      //   })
      //   state.schoolHomeInit = true
      // } else if (query.coachId) {
      //   state.coachId = query.coachId
      //   state.schoolId = null
      //   Storage.set('schoolHome', {
      //     type: 'coach',
      //     id: query.coachId
      //   })
      //   state.schoolHomeInit = true
      // } else {
      //   state.schoolId = null
      //   state.coachId = null
      // }
    },
    setSchoolHomeFromStorage(state, {type, id}) {
      if (state.schoolHomeInit) {
        return
      }
      if (type === 'coach') {
        state.coachId = id
        state.schoolId = null
        state.schoolHomeInit = true
      } else if (type === 'school') {
        state.schoolId = id
        state.coachId = null
        state.schoolHomeInit = true
      }
    },
    setLocation(state, {city}) {
      if (city) {
        state.location = city;
      }
    },
    setGPSLocation(state, {GPSLocation}) {
      state.GPSLocation = GPSLocation;
    },
    changeCarType(state, {carType}) {
      state.mine.carType = carType;
    },
    answer(state) {
      state.mine.answerCount += 1;
    },
    setSelectedLocation(state, {city}) {
      if (city) {
        state.selectedLocation = city;
      }
    },
    systemInfo(state, systemInfo) {
      state.systemInfo = systemInfo;
    },
    changeQuestionSetting(state, setting) {
      state.questionSetting = Object.assign(state.questionSetting, setting);
      Storage.set('questionSetting', state.questionSetting)
    },
    updateUser(state, user) {
      state.mine = Object.assign(state.mine, user);
    },
    topBar(state, {statusBarHeight, style, navbarHeight}) {
      state.topBar = {
        statusBarHeight,
        navbarHeight,
        style,
        height: statusBarHeight + navbarHeight
      }
    },
    checkedLogined(state) {
      state.checkedLogined = true
    },
    logout(state) {
      state.mine = null
      state.checkedLogined = false
    },
  },
  actions: {
    changeQuestionSetting({commit}, data) {
      commit('changeQuestionSetting', data)
    },
    answer({commit}) {
      commit('answer')
    },
    initCurrentTime({commit}, data) {
      setInterval(() => {
        commit('currentTime', Date.now())
      }, 1000)
    },
    setLocation({commit}, data) {
      commit('setLocation', data)
    },
    setGPSLocation({commit}, location) {
      commit('setGPSLocation', {
        GPSLocation: location
      })
    },
    setKemu1({commit}, data) {
      commit('setKemu1', data)
    },
    setKemu2({commit}, data) {
      commit('setKemu2', data)
    },
    setKemu3({commit}, data) {
      commit('setKemu3', data)
    },
    async setSelectedLocation({commit}, data) {
      if (data.city) {
        await commonApi.changeCity(data.city.code)
      }
      commit('setSelectedLocation', data)
    },
    //泛知识
    fanzhishiOpenVIP({commit}) {
      commit('updateUser', {vipEndAt: '2099-12-31'})
    },
    updateUser({commit}, user) {
      commit('updateUser', user)
    },
    async login({commit, state}, {provider, authResult, useNew, code, user}) {
      let userType = 0;
      try {
        let inviteUserId
        if (state.query) {
          inviteUserId = state.query.inviter
        }
        const res = await commonApi.thirdLogin(provider, authResult, code, user, useNew, inviteUserId)
        if (res.data.data && res.data.data.userType) {
          userType = res.data.data.userType;
        }
        commit('login', res.data.data)
        commit('checkedLogined')
      } catch (e) {
        console.log(e)
        throw e
      }
      return userType
    },
    async checkLogined({commit, state}) {
      if (!!state.mine) {
        return false
      }

      commit('checkedLogined')
      let authResult, provider, platform
      // #ifdef MP-TOUTIAO
      provider = 'toutiao'
      platform = 'toutiao_xcx'
      // #endif
      // #ifdef MP-WEIXIN
      provider = 'weixin'
      platform = 'weixin_xcx'
      // #endif

      if (provider) {
        authResult = await utils.uniLogin(provider)
        console.log(provider, authResult)
      }

      Storage.get('schoolHome').then(data => {
        console.log('setSchoolHomeFromStorage', data)
        if (data) {
          commit('setSchoolHomeFromStorage', data)
        }
      })
      Storage.get('questionSetting').then(data => {
        console.log('questionSetting', data)
        if (data) {
          commit('changeQuestionSetting', data)
        }
      })
      const res = await commonApi.autoLogin(platform, authResult)
      if (res.data.data.location) {
        commit('setLocation', {city: res.data.data.location})
      }

      if (res.data.data.user.anonymous) {
        await Storage.set('account', res.data.data.user.account)
      } else {
        await Storage.del('account')
      }
      let location = await Storage.get('location')
      if (location) {
        commit('setSelectedLocation', {city: location})
      }

      commit('login', res.data.data)
      commit('settings', res.data.data)
      const list = []
      // const ids = res.data.data.settings.productIds
      // const res3 = await productApi.list(ids + ',3,2')
      // const res3 = await productApi.list('116,117,118,3,2')
      // let ids = res.data.data.settings.productIds || ''
      let ids = productUtils.productIds()
      let idsLength = ids[0].split(',').length

      if (res.data.data.settings.tiyanProductId) {
        if (ids) {
          ids += ','
        }
        ids += res.data.data.settings.tiyanProductId
      }
      const res3 = await productApi.list(ids)
      commit('vipProducts', res3.data.data.list.splice(0, idsLength))
      commit('tiyanProduct', res3.data.data.list.splice(0, 1)[0])

      return true
    },

    async refreshUser({commit, state}) {
      const res = await commonApi.refreshUser()
      commit('login', res.data.data)
    },

    async logout({commit}) {
      await commonApi.logout()
      uni.clearStorageSync()
      tokenManager.clear()
      commit('logout')
    },

    async unregister({commit}) {
      await commonApi.unregister()
      uni.clearStorageSync()
      tokenManager.clear()
      commit('logout')
    },

    async initSetting({commit}, {env, systemInfo}) {
      // #ifdef MP-TOUTIAO
      commit('topBar', {statusBarHeight: systemInfo.statusBarHeight, navbarHeight: 44, style: 'default'})
      // #endif

      // #ifdef H5
      commit('topBar', {statusBarHeight: 20, style: 'custom', navbarHeight: 44})
      // systemInfo['uniPlatform'] = 'mp-toutiao'
      // systemInfo['packageName'] = 'tt685f1ee2f7601aff01'
      // systemInfo['uniPlatform'] = 'mp-weixin'
      // systemInfo['packageName'] = 'wx3680d1b2ba8d7629'
      systemInfo['uniPlatform'] = 'app'
      systemInfo['packageName'] = 'com.jiakao.qnw.zs'
      // #endif
      // systemInfo['uniPlatform'] = 'app'
      // systemInfo['packageName'] = 'com.qw.jiakao'
      // #ifndef MP-TOUTIAO || H5
      commit('topBar', {statusBarHeight: systemInfo.statusBarHeight, style: 'custom', navbarHeight: 44})
      // #endif
      systemInfo.appChannel = ''
      systemInfo.adChannel = ''
      // #ifdef APP-PLUS
      if (systemInfo.osName === 'android') {
        systemInfo.appChannel = 'UMENG_CHANNEL_' + (plus.runtime.channel || utils.getAndroidMetaData('UMENG_CHANNEL'))
        systemInfo.androidId = utils.getAndroidId()
        // utils.uploadInstalledApps()

        // await new Promise(resolve => {
        //   plus.device.getInfo({
        //     success: (e) => {
        //       systemInfo.imei = e.imei
        //       console.log('getDeviceInfo success: ', e);
        //       resolve()
        //     },
        //     fail: (e) => {
        //       console.log('getDeviceInfo failed: ', e);
        //       resolve()
        //     }
        //   });
        // })

        await new Promise(resolve => {
          plus.device.getOAID({
            success: (e) => {
              console.log('getOAID success', e)
              systemInfo.oaid = e.oaid
              resolve()
            },
            fail: (e) => {
              console.log('getOAID fail', e)
              resolve()
            }
          })
        })
      } else {
        systemInfo.appChannel = 'ios'
      }
      // #endif
      // #ifdef MP
      const launchOptionsSync = uni.getLaunchOptionsSync()
      systemInfo.adChannel = launchOptionsSync.query.ad_channel
      console.log('getLaunchOptionsSync', launchOptionsSync)
      // #endif


      commit('systemInfo', systemInfo)
      commit('env', env)
    },

    initQuery({commit}, {query = {}}) {
      console.log('initQuery query', query)
      commit('query', {query})
      // commit('query', {query: {inviter: 1293}})
    },

    async changeCarType({commit}, carType) {
      await commonApi.updateCarType(carType)
      uni.$emit('changeCarType', carType)
      uni.showToast({
        title: '车型切换成功！',
        icon: 'none',
        duration: 2000
      })
      commit('changeCarType', {carType})
    },

    async changeKemu({commit}, kemu) {
      await commonApi.updateKemu(kemu)
    }
  },
  getters: {
    loginBeforePay: state => {
      // return state.systemInfo.appChannel === 'UMENG_CHANNEL_1003m'
      return true
    },
    isLogined: state => {
      if (state.mine) {
        return true
      }
      return false
    },
    hideAD: state => {
      return state.settings ? state.settings.hideAD : false
    },
    needShowAD: state => {
      if (state.mine && (state.mine.vipEndAt1 || state.mine.vipEndAt2 || state.mine.vipEndAt3 || state.mine.vipEndAt4)) {
        return false
      }

      const ADAnswerCount = parseInt(state.settings.ADAnswerCount || 0)

      if (ADAnswerCount) {
        return state.mine.answerCount >= ADAnswerCount
      }

      return false
    },
    needShowGateway: state => {
      const noVIPgatewayAnswerCount = parseInt(state.settings.noVIPgatewayAnswerCount || 0)

      if (noVIPgatewayAnswerCount) {
        return state.mine.answerCount >= noVIPgatewayAnswerCount
      }

      return false
    },
    needShowChapingAD: state => {
      if (state.mine && state.settings) {
        const chapingAdAnswerCount = parseInt(state.settings.chapingAdAnswerCount || 0)

        if (chapingAdAnswerCount) {
          return state.mine.answerCount >= chapingAdAnswerCount
        }
      }

      return false
    },
    needShowKaipingAD: state => {
      if (state.mine && state.settings) {
        const KaipingADAnswerCount = parseInt(state.settings.KaipingADAnswerCount || 0)
        // console.log('KaipingADAnswerCount', KaipingADAnswerCount)
        // console.log('answerCount', state.mine.answerCount)
        if (KaipingADAnswerCount) {
          return state.mine.answerCount >= KaipingADAnswerCount
        }
      }

      return false
    },
    haveAuths: state => {
      if (state.mine) {
        return state.mine.auths.length
      }
      return false
    },
    vipGateway: state => {
      return 'all11'
    },
    kaobuguo: state => {
      return state.settings ? state.settings.kaobuguo : 0
    },
    selectedLocation: state => {
      return state.selectedLocation || state.location
    },
    location: state => {
      return state.location
    },
    GPSLocation: state => {
      return state.GPSLocation
    },
    currentTime: state => {
      return state.currentTime
    },
    mine: state => {
      return state.mine
    },
    kemu1: state => {
      return state.kemu1
    },
    kemu2: state => {
      return state.kemu2
    },
    kemu3: state => {
      return state.kemu3
    },
    coachId: state => {
      return state.coachId
    },
    topBar: state => {
      return state.topBar
    },
    questionSetting: state => {
      return state.questionSetting
    },
    settings: state => {
      return state.settings
    },
    adChaping: state => {
      return parseInt((state.settings ? (state.settings.adChaping || 0) : 0)) * 1000
    },
    schoolId: state => {
      return state.settings ? state.settings.schoolId : null
    },
    fanzhishiVIPProductId: state => {
      return state.settings ? state.settings.fanzhishiVIPProductId : null
    },
    review: state => {
      return state.settings ? state.settings.review : true
    },
    zhuomian: state => {
      return state.settings ? state.settings.zhuomian : 0
    },
    appType: state => {
      return state.settings ? state.settings.appType : 0
    },
    splashVIPAd: state => {
      return state.settings ? state.settings.splashVIPAd : 0
    },
    vipProducts: state => {
      return state.vipProducts || []
    },
    tiyanProduct: state => {
      return state.tiyanProduct
    },
    mainProduct: state => {
      return state.vipProducts[0]
    },
    canPay: state => {
      if (state.systemInfo.uniPlatform === 'mp-weixin' || state.systemInfo.uniPlatform === 'mp-toutiao') {
        if (state.systemInfo.osName === 'ios') {
          return false
        }
      }

      return true
    },
    banners: state => {
      return state.settings ? state.settings.banners : []
    },
    openYuyin: state => {
      return state.settings ? state.settings.yuyin : 0
    },
    eventTime: state => {
      const time = state.settings ? parseInt(state.settings.eventTime) : 10000
      return time || 10000
    },
    systemInfo: state => {
      return state.systemInfo
    },
    carType: state => {
      if (state.mine)
        return state.mine.carType
      return 1
    },
    carTypeStr: state => {
      let carType = 1
      if (state.mine)
        carType = state.mine.carType
      return ['小车', '货车', '客车', '摩托车'][carType - 1]
    },
    appName: state => {
      if (state.settingsInited) {
        return state.settings.appName
      }
      return ''
    },
    env: state => {
      return state.env
    },
    isNewUser: state => {
      if (state.mine && (state.mine.vipEndAt || state.mine.vipExpiredStr)) {
        return false
      }
      return true
    },
    query: state => {
      return state.query
    },
    isAllVIP: state => {
      if (state.mine && state.mine.vipEndAt1 && state.mine.vipEndAt2 && state.mine.vipEndAt3 && state.mine.vipEndAt4) {
        return true
      }
      return false
    },
    isForeverVIP: state => {
      if (state.mine && state.mine.vipEndAt1 && state.mine.vipEndAt2 && state.mine.vipEndAt3 && state.mine.vipEndAt4) {
        return productUtils.isForeverVIP(state.mine.vipEndAt1)
      }
      return false
    },
    haveVIP: state => {
      if (state.mine && (state.mine.vipEndAt1 || state.mine.vipEndAt2 || state.mine.vipEndAt3 || state.mine.vipEndAt4)) {
        return true
      }
      return false
    },
    isKemu1VIP: state => {
      if (state.mine && state.mine.vipEndAt1) {
        return true
      }
      return false
    },
    isKemu2VIP: state => {
      if (state.mine && state.mine.vipEndAt2) {
        return true
      }
      return false
    },
    isKemu3VIP: state => {
      if (state.mine && state.mine.vipEndAt3) {
        return true
      }
      return false
    },
    isKemu4VIP: state => {
      if (state.mine && state.mine.vipEndAt4) {
        return true
      }
      return false
    },
    platform: state => {
      if (state.systemInfo.uniPlatform === 'app') {
        return state.systemInfo.osName
      }

      return state.systemInfo.uniPlatform
    },
    os: state => {
      return state.systemInfo.osName
    },
    jiliAdId: state => {
      return state.settings ? state.settings.jiliAdId : null
    },
    chapingAdId: state => {
      return state.settings ? state.settings.chapingAdId : null
    },
    bannerAd1Id: state => {
      return state.settings ? state.settings.bannerAd1Id : null
    },
    bannerAd2Id: state => {
      return state.settings ? state.settings.bannerAd2Id : null
    },
    bannerAd3Id: state => {
      return state.settings ? state.settings.bannerAd3Id : null
    },
    splashBuy: state => {
      return state.settings ? state.settings.splashBuy : 1
    },
    homePop: state => {
      return state.settings ? state.settings.homePop : 1
    },
  }
})
export default store
